package com.org.cloud.lg.custom;
import com.org.cloud.lg.constants.SecurityConstants;
import com.org.cloud.lg.utils.BaseContextKit;
import com.org.cloud.lg.utils.Checker;
import com.org.cloud.lg.utils.SpringContextHolder;
import lombok.Data;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/*
 * @Author LG
 * @Description 验证jwt是否有效
 * @Date 11:03 2019/4/30
 * @Param
 * @return
 **/
@Data
public class CustomJwtAuthenticationFilter extends OncePerRequestFilter {

	private RequestMatcher matcher;

	private JwtTokenStore tokenStore;

	TokenExtractor tokenExtractor=SpringContextHolder.getBean(TokenExtractor.class);

	public CustomJwtAuthenticationFilter(RequestMatcher matcher) {
		this.matcher = matcher;

	}
	public CustomJwtAuthenticationFilter(RequestMatcher matcher, JwtTokenStore tokenStore) {
		this.matcher = matcher;
		this.tokenStore = tokenStore;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//提取token
		Authentication authentication = tokenExtractor.extract(request);
		if (Checker.BeNull(authentication)) {
			throw new InvalidTokenException("Invalid jwt token can't be null!");
		}
		String tokenValue = authentication.getPrincipal().toString();
		//读取token信息
		OAuth2Authentication oauth = tokenStore.readAuthentication(tokenValue);
		//读取详细信息-commonJwtAccessConvert extractAuthentication方法
		Map<String, Object> details = (Map<String, Object>)oauth.getDetails();
		String uid = Checker.BeNull(details.get(SecurityConstants.USER_ID)) ? null : details.get(SecurityConstants.USER_ID).toString();
		String deptId = Checker.BeNull(details.get(SecurityConstants.DEPT_ID)) ? null : details.get(SecurityConstants.DEPT_ID).toString();
		if (Checker.BeEmpty(uid)) {
			throw new InvalidTokenException("Invalid jwt token!");
		}
		BaseContextKit.setUserID(uid);
		try {
			filterChain.doFilter(request, response);
		}finally {
			BaseContextKit.remove();
		}
	}

}
